<?php

namespace App\Http\Controllers\Admin;

use App\Models\Area;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AreaController extends Controller
{
    public function index(Request $request)
    {
        $model = Area::query();
        $data = $model->orderBy('sort', 'asc')->orderBy('id', 'desc')->get()->toArray();
        $result = getListTree($data, 'id', 'par_id');
        return showMsg('操作成功', 200, $result);
    }

    public function getArea()
    {
        $model = Area::query();
        $model = $model->with('children');
        $model = $model->where('par_id', 0);
        $model = $model->orderBy('sort', 'asc');
        $result = $model->get();
        return showMsg('操作成功', 200, $result);
    }


    public function detail(Request $request)
    {
        $id = $request->get('id');
        $result = Area::findOrFail($id);
        if (!$result) {
            return showMsg('信息已删除', 201, $result);
        }
        return showMsg('操作成功', 200, $result);
    }


    public function beforeSave(Request $request)
    {
        $id = $request->get('id');
        $data = $request->all();
        if ($id) {
            $article = Area::findOrFail($id);
            if ($article->update($data)) {
                return showMsg('更新成功', 200);
            }
        } else {
            Area::create($data);
            return showMsg('添加成功', 200);
        }
    }


    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)) {
            return showMsg('请选择操作项', 201);
        }
        if (is_array($ids)) {
            foreach ($ids as $v) {
                Area::destroy('id', $v);
            }
        } else {
            Area::destroy('id', $ids);
        }
        return showMsg('删除成功', 200);
    }

}
